package com.ybb.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    private static String driver;
    private static String url;
    private static String userName;
    private static String password;

    static {
        InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("database.properties");
        Properties properties = new Properties();



        try {
            properties.load(resourceAsStream);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            userName = properties.getProperty("userName");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //获取数据库链接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, userName, password);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;


    }


    //关闭资源
    public static void close(ResultSet rs, Statement statement, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    //工具类查询列表
    public static ResultSet query(PreparedStatement statement, Object[] params) {
        ResultSet resultSet = null;
        try {
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i + 1, params[i]);
            }
            resultSet = statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return resultSet;
    }

    //增删改操作
    public static int update(PreparedStatement statement, Object[] params) {
        int effectRows = 0;
        for (int i = 0; i < params.length; i++) {
            try {
                statement.setObject(i + 1, params[i]);

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        try {
            effectRows = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return effectRows;
    }

}
